package com.dave.admin.util;

import com.dave.admin.config.auth.pojo.BossUserDetails;
import com.dave.admin.modular.boss.entity.Permission;
import com.dave.admin.modular.boss.entity.UserAdmin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.List;
import java.util.Optional;

/**
 * spring security 工具类
 *
 * @author Dave
 */
public abstract class SecurityUtil {


    private static Logger logger = LoggerFactory.getLogger(SecurityUtil.class);

    /**
     * 获取当前Security对象
     */
    public static BossUserDetails getBossUserDetails() {
        if (SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof String) {
            return new BossUserDetails(UserAdmin.builder().nickName
                    ((String) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).build()
                    , null);
        }
        return (BossUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }

    /**
     * 获取当前用户权限
     */
    public static List<Permission> getPermissionList() {
        return getBossUserDetails().getPermissionList();
    }

    /**
     * 获取当前用户信息
     */
    public static UserAdmin getUserAdmin() {
        return Optional.ofNullable(getBossUserDetails()).orElse(new BossUserDetails(new UserAdmin(), null)).getUserAdmin();
    }

    /**
     * 获取当前用户名
     */
    public static String getUserAdminName() {
        return getUserAdmin().getUsername();
    }
}

